<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <!-- canvas 绘制验证码。 -->
</head>
<body>
  <input type="text" id="input" placeholder="请输入验证码" />
  <button id="button">提交</button>
  <canvas id="canvas" width="150" height="50"></canvas>
  <script>
      function randomNum(min, max) {
          return Math.floor(Math.random() * (max - min) + min);
      }
      function randomColor(min, max) {//获取随机颜色
          var _r = randomNum(min, max);
          var _g = randomNum(min, max);
          var _b = randomNum(min, max);
          return "rgb(" + _r + "," + _g + "," + _b + ")";
      }
      document.getElementById("canvas").onclick = function (e) {
          e.preventDefault();
          drawPic();
      };
      document.getElementById("button").onclick = function (e) {
          inputValue = document.getElementById("input").value;
          var count = 0;
          for (var i = 0; i < inputValue.length; i++) {//判断输入框中的内容与canvas生成验证码是否相同
              for (var j = i; j < picTxt.length; j++) {
                  if (inputValue[i].toLowerCase() == picTxt[j].toLowerCase()) {
                      count++;
                      break
                  } else {
                      break
                  }
              }
          }
          if (count == 4) {
              alert("验证通过")//相同则验证通过
          } else {
              drawPic();//不同则更新canvas中的验证码
          }
      };


      function drawPic() {//绘制验证码
          var canvas = document.getElementById("canvas");
          var _str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
          picTxt = "";
          var num = 4;
          var _width = canvas.width;
          var _height = canvas.height;
          var ctx = canvas.getContext("2d");
          ctx.textBaseline = "bottom";
          ctx.fillStyle = randomColor(180, 240);
          ctx.fillRect(0, 0, _width, _height);
          for (var i = 0; i < num; i++) {
              var x = (_width - 10) / num * i + 10;
              var y = randomNum(_height / 2, _height);
              var deg = randomNum(-45, 45);//验证码会有不同程度的偏斜
              var txt = _str[randomNum(0, _str.length)];//随机获取一个数字
              picTxt += txt;
              ctx.fillStyle = randomColor(10, 100);
              ctx.font = randomNum(16, 40) + "px SimHei";
              ctx.translate(x, y);
              ctx.rotate(deg * Math.PI / 180);
              ctx.fillText(txt, 0, 0);
              ctx.rotate(-deg * Math.PI / 180);
              ctx.translate(-x, -y);
          }
      }
      drawPic();
  </script>
</body>
</html>